<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { useDebounceFn } from '@vueuse/core'
import VirtualList from '@/components/VirtualList.vue'
import { queryMateriel } from '@/api/Base/repositoryManager'
import { to } from '@/utils/routerUtil'

interface Product {
  sProductNo: string
  sPhotoUrl: string
  sProductClass: string
  sProductPublicClass: string
  sProductName: string
  sRecommendGrade: string
  effectiveQuantity: number
  status: number
}

interface ProductManagerState {
  search: {
    searchText: string
    status: number
  }
  page: number
  pageSize: number
  loading: boolean
  finished: boolean
  reload: () => void
  loadMore: () => void
}

// 组件引用
const productListContainer = ref<InstanceType<typeof VirtualList> | null>(null)

// 状态管理
const ProductManager = reactive<ProductManagerState>({
  search: {
    searchText: '',
    status: 0
  },
  page: 1,
  pageSize: 20,
  loading: false,
  finished: false,
  reload: () => {
    console.log('[ProductManager] 执行重置')
    productListContainer.value?.reset()
  },
  loadMore: () => {
    console.log('[ProductManager] 手动加载更多')
    productListContainer.value?.loadMore()
  }
})

// 安全解析 JSON
const safeParseJSON = (str: string) => {
  try {
    return JSON.parse(str)
  } catch {
    console.warn('[ProductManager] 无效的 JSON 字符串:', str)
    return []
  }
}

// 数据加载器
const loader = async (page: number) => {
  try {
    console.log('[ProductManager] 加载数据', {
      page,
      searchKey: ProductManager.search.searchText
    })
    
    const res = await queryMateriel({
      page,
      pageSize: ProductManager.pageSize,
      searchKey: ProductManager.search.searchText
    })
    
    console.log('[ProductManager] 加载完成', {
      page,
      count: res.data.list.length,
      total: res.data.total
    })
    
    return res.data.list
  } catch (err) {
    console.error('[ProductManager] 加载失败', err)
    throw err
  }
}

// 搜索处理
const handleSearchInput = useDebounceFn((value: string) => {
  console.log('[ProductManager] 执行搜索，关键词:', value)
  ProductManager.search.searchText = value
  ProductManager.page = 1
  ProductManager.finished = false
  
  // 重置滚动位置
  productListContainer.value?.$el.scrollTo({ top: 0, behavior: 'auto' })
  
  // 重新加载数据
  productListContainer.value?.reset()
  nextTick(() => {
    productListContainer.value?.loadMore()
  })
}, 500, { maxWait: 1000 })

// 页面导航
const router = useRouter()
function onBack() {
  if (window.history.state.back) {
    history.back()
  } else {
    router.replace('/')
  }
}

// 初始化
onMounted(() => {
  console.log('[ProductManager] 组件挂载')
  ProductManager.reload()
})
</script>

<template>
  <VanNavBar :fixed="true" clickable left-arrow @click-left="onBack">
    <template #title>
      <div class="flex flex-row gap-8">
        <van-search
          class="search"
          shape="round"
          v-model="ProductManager.search.searchText"
          placeholder="请输入品名/料号"
          @update:model-value="handleSearchInput"
        />
        <div class="flex justify-center items-center">
          <van-image width="16" height="16" src="/productManager/扫码.png" />
        </div>
      </div>
    </template>
    <template #right>
      <div class="scan flex justify-center items-center">
        <van-image width="16" height="16" src="/productManager/添加.png" />
      </div>
    </template>
  </VanNavBar>

  <div
    class="card m-[4rem] flex flex-col gap-[10px] mt-[70px]"
    style="height: calc(100vh - 170px); min-height: 300px"
  >
    <VirtualList
      ref="productListContainer"
      :loader="loader"
      :item-height="250"
      :gap="10"
      :initial-page="ProductManager.page"
      :page-size="ProductManager.pageSize"
      @update:loading="(val) => (ProductManager.loading = val)"
      @update:finished="(val) => (ProductManager.finished = val)"
    >
      <template #default="{ item, index }">
        <div
          :key="index"
          @click="to(`ProductInfo?id=${item.sProductNo}`)"
          class="product-item h-[250px] p-[10px] rounded-lg bg-white"
        >
          <EImage
            :photo-url="item.sPhotoUrl || '/'"
            :water-mark="item.status === 0 ? '停用' : ''"
            lazy
          />
          <div class="product-info">
            <h1 class="product-title">
              {{
                (safeParseJSON(item.sProductClass) || []).join(',') +
                (safeParseJSON(item.sProductPublicClass) || []).join(',') +
                item.sProductName
              }}
            </h1>
            <h1 class="text-[10px] text-coolgray leading-none">
              料号:{{ item.sProductNo }}
            </h1>
            <h1 class="text-[10px] text-coolgray leading-none">
              推荐等级:{{ item.sRecommendGrade }}
            </h1>
            <h1 class="w-[100%] text-right text-coolgray text-[10px] leading-none">
              库存{{ item.effectiveQuantity }}
            </h1>
          </div>
        </div>
      </template>

      <template #loading>
        <van-loading vertical>
          <template #icon>
            <van-icon name="star-o" size="30" />
          </template>
          加载中...
        </van-loading>
      </template>

      <template #finished>
        <div class="text-center py-4 text-coolgray">没有更多数据了</div>
      </template>
    </VirtualList>
  </div>
</template>

<style lang="less" scoped>
.card {
  border-radius: 5px;
  opacity: 1;
}

.search {
  height: 2rem;
  border-radius: 5px;
  opacity: 1;
  background: #ffffff;
}

.product-item {
  flex: 0 0 calc(50% - 5px);
  background: white;
  border-radius: 8px;
  margin-bottom: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;

  .product-info {
    padding: 8px;

    .product-title {
      font-size: 12px;
      line-height: 1.4;
      height: 34px;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
    }

    .product-details {
      font-size: 10px;
      color: #666;
      display: flex;
      flex-direction: column;
      gap: 4px;

      .stock {
        text-align: right;
        margin-top: 4px;
      }
    }
  }
}
</style>
